﻿namespace MultiTenant.FreeSql;

/// <summary>
/// 
/// </summary>
public class TenantStore
{
    private IFreeSql _freeSql;
    private ICache _cache;
    /// <summary>
    /// 
    /// </summary>
    /// <param name="freeSql"></param>
    /// <param name="cache"></param>
    public TenantStore(IFreeSql freeSql, ICache cache)
    {
        _freeSql = freeSql;
        _cache = cache;


    }
    public async Task<IEnumerable<Tenant>> GetAllAsync()
    {
        return await _freeSql.Select<Tenant>()
          .AsType(typeof(Tenant))
        .ToListAsync();
    }

    public async Task<bool> TryAddAsync(Tenant tenantInfo)
    {
        return await _freeSql.Insert<Tenant>().AsType(typeof(Tenant))
             .AppendData(tenantInfo)
             .ExecuteAffrowsAsync() > 0;
    }

    public async Task<Tenant?> TryGetAsync(long id)
    {
        return await _freeSql.Select<Tenant>()
            .AsType(typeof(Tenant))
          .Where(ti => ti.Id == id)
          .ToOneAsync();

    }



    public async Task<Tenant?> TryGetByIdentifierAsync(string identifier)
    {
        var key = $"tenant_{identifier}";
        Tenant? tenant = null;
        if (_cache.Exists(key))
        {
            tenant = _cache.Get<Tenant>(key);
        }
        else
        {
            tenant = await _freeSql.Select<Tenant>()
          .Where(ti => ti.Identifier == identifier)
          .ToOneAsync();
            _cache.Set(key, tenant, TimeSpan.FromHours(8));
        }
        return tenant;
    }

    public async Task<bool> TryRemoveAsync(string identifier)
    {
        return await _freeSql.Delete<Tenant>()
            .Where(x => x.Identifier == identifier)
            .ExecuteAffrowsAsync() > 0;
    }

    public async Task<bool> TryUpdateAsync(Tenant tenantInfo)
    {
        return await _freeSql.Update<Tenant>()
          .SetSource(tenantInfo)
          .ExecuteAffrowsAsync() > 0;
    }
}